package com.tony.dao.impl;

import com.tony.bean.ArticleInfo;
import com.tony.dao.ArticleDao;
import com.tony.dao.RedisGeneratorDao;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.stereotype.Component;
import org.springframework.test.annotation.Commit;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by Tony on 2017/1/4.
 */
@Component
public class ArticleDaoImpl extends RedisGeneratorDao<String,ArticleInfo>  implements ArticleDao {
    public boolean postArticle(String user,String title,String link){
        Long articleId = getNewId("article:");

        HashOperations<String,String,String> hashOps = redisTemplate.opsForHash();

        String articleKey = "article:" + articleId;

        Map<String, String> map = new HashMap<String, String>();
        map.put("title", title);
        map.put("link", link);
        map.put("usr", user);
        map.put("time", String.valueOf(System.currentTimeMillis()));

        hashOps.putAll(articleKey,map);
        return true;

    };

    public Long getNewId(final String key){
        return redisTemplate.execute(new RedisCallback<Long>() {
            public Long doInRedis(RedisConnection redisConnection) throws DataAccessException {
                byte[] redisKey = getRedisSerializer().serialize(key);
                return redisConnection.incr(redisKey);
            }
        });
    }


}
